package com.zjgeport.zjgdanger.Exception;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.soar.PageInfo;
import com.soar.controller.PullDownView;
import com.soar.util.net.rmi.httpxml.HttpCallBack;
import com.soar.util.net.rmi.httpxml.HttpClient;
import com.soar.util.net.rmi.httpxml.HttpMethod;
import com.soar.util.net.rmi.httpxml.HttpResult;
import com.zjgeport.zjgdanger.LoginActivity;
import com.zjgeport.zjgdanger.R;
import com.zjgeport.zjgdanger.common.ParamCommon;
import com.zjgeport.zjgdanger.model.myApplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link IllegalDoFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link IllegalDoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class IllegalDoFragment extends Fragment {

    private PullDownView mPullDownView;

    /** Handler What加载数据完毕 **/
    private static final int WHAT_DID_LOAD_DATA = 0;

    /** Handler What更新数据完毕 **/
    private static final int WHAT_DID_REFRESH = 1;

    /** Handler What更多数据完毕 **/
    private static final int WHAT_DID_MORE = 2;

    private ListView mListView;

    private EditText searchText;

    private MyCustomAdapter adapter;

    /** 分页信息 **/
    protected PageInfo pageInfo = new PageInfo();

    private List<HashMap<String, String>> dataList = new ArrayList<HashMap<String, String>>();

    private List<HashMap<String, String>> dataMore = new ArrayList<HashMap<String, String>>(); // 更多数据列表

    private String sql= "";

    private String keyword = "";

    private Integer currentPage = 1;

    private String pageSize = "15";

    private IntentFilter intentFilter;
    private BroadcastReceiver broadReceiver;

    @Override
    public void onResume() {
        super.onResume();
        getTankList();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_illegal_do, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView()
    {
//        searchText = getActivity().findViewById(R.id.search_content1);
//        searchText.setHint("请输入储罐代码或公司名称");
//        searchText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//
//                @Override
//                public boolean onEditorAction(TextView v, int actionId,
//                                              KeyEvent event) {
//                    if ((actionId == 0 || actionId == 3) && event != null) {
//
//                        keyword = searchText.getText().toString();
//                        getTankList();
//
//                    }
//                    return false;
//                }
//            });
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.text_change");
        broadReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                Bundle data = intent.getExtras();
                if (data.getString("flag").equals("1"))
                {
                    keyword = data.getString("keyword");
                    getTankList();
                }

            }
        };
        getActivity().registerReceiver(broadReceiver,intentFilter);


        float scale = getActivity().getResources().getDisplayMetrics().density;
        int height = (int) (70 * scale + 0.5f);
		/*
		 * 1.使用PullDownView 2.设置OnPullDownListener 3.从mPullDownView里面获取ListView
		 */
        mPullDownView = new PullDownView(getActivity(), height);
        mPullDownView = (PullDownView) getActivity().findViewById(R.id.pull_down_view2);
        adapter = new MyCustomAdapter(getActivity(), dataList);
        mPullDownView.setOnPullDownListener(new PullDownView.OnPullDownListener() {

            public void onRefresh()
            {
                HttpMethod method = new HttpMethod();
                final HashMap<String, String> map = new HashMap<String, String>();
                currentPage = 1;
                map.put("keyword", keyword);
                map.put("pageSize",pageSize);
                map.put("pageNo",currentPage.toString());
                map.put("TOKEN", myApplication.getUser().getToken());
                method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
                method.setClassPath("com.mobile.Execute");
                method.setMethodName("selectIllegaldoingListInfo");
                method.setKvdata(map);
                final List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
                HttpClient.postdata(new Button(getActivity()), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
                    @Override
                    public void run(HttpResult result) {
                        if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {
                            List<HashMap<String, String>> data1 = result.getDataSet();
                            if (data1 != null && data1.size() != 0) {
                                data.addAll(data1);
                            }

                        } else {
                            mPullDownView.notifyDidLoad();
                            Toast.makeText(getActivity().getApplication(), result.getResultMessage(), 1).show();
                            if (result.getResultCode().equals("90"))
                            {
                                Intent intent = new Intent(getActivity(),LoginActivity.class);
                                startActivity(intent);
                            }
                        }
                        // 刷新UI
                        Looper mainLooper = Looper.getMainLooper();
                        MyHandler handler = new MyHandler(mainLooper);
                        Message msg = new Message();
                        msg.what = WHAT_DID_REFRESH;
                        msg.obj = data;
                        handler.sendMessage(msg);

                    }
                });
            }


            public void onMore()
            {
                HttpMethod method = new HttpMethod();
                final HashMap<String, String> map = new HashMap<String, String>();
                currentPage = currentPage + 1;
                map.put("keyword", keyword);
                map.put("pageSize",pageSize);
                map.put("pageNo",currentPage.toString());
                map.put("TOKEN", myApplication.getUser().getToken());
                method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
                method.setClassPath("com.mobile.Execute");
                method.setMethodName("selectIllegaldoingListInfo");
                method.setKvdata(map);
                final List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
                HttpClient.postdata(new Button(getActivity()), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
                            @Override
                            public void run(HttpResult result) {
                                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {
                                    dataMore = result.getDataSet();
                                    if (dataMore != null && dataMore.size() != 0) {
                                        data.addAll(dataMore);
                                    }

                                } else {
                                    mPullDownView.notifyDidLoad();
                                    Toast.makeText(getActivity().getApplication(), result.getResultMessage(), 1).show();
                                    if (result.getResultCode().equals("90"))
                                    {
                                        Intent intent = new Intent(getActivity(),LoginActivity.class);
                                        startActivity(intent);
                                    }
                                }
                                // 刷新UI
                                if (data.size() >0)
                                {
                                    Looper mainLooper = Looper.getMainLooper();
                                    MyHandler handler = new MyHandler(mainLooper);
                                    Message msg = new Message();
                                    msg.what = WHAT_DID_MORE;
                                    msg.obj = data;
                                    handler.sendMessage(msg);
                                }
                                else{
                                    Looper mainLooper = Looper.getMainLooper();
                                    MyHandler handler = new MyHandler(mainLooper);
                                    Message msg = new Message();
                                    msg.what = 4;
                                    msg.obj = data;
                                    handler.sendMessage(msg);
                                }

                            }
                        });
            }
        });

        mListView = mPullDownView.getListView();
        mListView.setDivider(getResources().getDrawable(R.color.white));
        mListView.setSelector(R.color.ap_sel);// 取消点击背景
        mListView.setAdapter(adapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
            {
                Intent intent = new Intent(getActivity(), IllegalDetailActivity.class);
                intent.putExtra("ID", dataList.get(arg2).get("ID").toString());
                intent.putExtra("FLAG", "1");
                startActivity(intent);
            }
        });
        // 设置可以自动获取更多 滑到最后一个自动获取 改成false将禁用自动获取更多
        mPullDownView.enableAutoFetchMore(false, 1);
        mPullDownView.notifyDidLoad();
        getTankList();

    }


    /**
     * 初始化数据列表信息
     */
    private void getTankList() {

        HttpMethod method = new HttpMethod();
        final HashMap<String, String> map = new HashMap<String, String>();
        map.put("keyword", keyword);
        map.put("pageSize",pageSize);
        map.put("pageNo",currentPage.toString());
        map.put("TOKEN", myApplication.getUser().getToken());
        method.setAction(HttpMethod.SOAR_HTTP_METHOD_ACTION_EXEC);
        method.setClassPath("com.mobile.Execute");
        method.setMethodName("selectIllegaldoingListInfo");
        method.setKvdata(map);
        final List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
        HttpClient.postdata(new Button(getActivity()), method, ParamCommon.ptl_server_url, true, new HttpCallBack() {
            @Override
            public void run(HttpResult result) {
                if (result.getResultCode().equals(HttpResult.SOAR_HTTP_STATUS_CODE_SUCCESS)) {
                    List<HashMap<String, String>> data1 = result.getDataSet();
                    if (data1 != null && data1.size() != 0) {
                        data.addAll(data1);
                    }

                } else {
                    mPullDownView.notifyDidLoad();
                    Toast.makeText(getActivity().getApplication(), result.getResultMessage(), 1).show();
                    if (result.getResultCode().equals("90"))
                    {
                        Intent intent = new Intent(getActivity(),LoginActivity.class);
                        startActivity(intent);
                    }
                }
                // 刷新UI
                Looper mainLooper = Looper.getMainLooper();
                MyHandler handler = new MyHandler(mainLooper);
                Message msg = new Message();
                msg.what = WHAT_DID_LOAD_DATA;
                msg.obj = data;
                handler.sendMessage(msg);

            }
        });
    }




    private class MyHandler extends Handler
    {
        public MyHandler(Looper looper)
        {
            super(looper);
        }

        @SuppressWarnings("unchecked")
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case WHAT_DID_LOAD_DATA:
                    List<HashMap<String, String>> dataNewList = (List<HashMap<String, String>>) msg.obj;
                    List<HashMap<String, String>> dataCacheList = new ArrayList<HashMap<String, String>>();
                    if (dataNewList != null && dataNewList.size() != 0)
                    {
                        dataList.clear();
                        for (int i = 0; i < dataNewList.size(); i++)
                        {
                            dataList.add(dataNewList.get(i));
                        }
                    }
                    else
                    {
                        if (dataCacheList != null && dataCacheList.size() != 0)
                        {
                            dataList.clear();
                            for (int i = 0; i < dataCacheList.size(); i++)
                            {
                                dataList.add(dataCacheList.get(i));
                            }
                        }
                        else {
                            dataList.clear();
                        }
                    }
                    adapter.notifyDataSetChanged();
                    mPullDownView.notifyDidLoad();
                    break;
                case WHAT_DID_REFRESH:
                    List<HashMap<String, String>> dataNewList2 = (List<HashMap<String, String>>) msg.obj;
                    List<HashMap<String, String>> dataCacheList2 = new ArrayList<HashMap<String, String>>();
                    if (dataNewList2 != null && dataNewList2.size() != 0)
                    {
                        dataList.clear();
                        for (int i = 0; i < dataNewList2.size(); i++)
                        {
                            dataList.add(dataNewList2.get(i));
                        }
                    }
                    else
                    {
                        if (dataCacheList2 != null && dataCacheList2.size() != 0)
                        {
                            dataList.clear();
                            for (int i = 0; i < dataCacheList2.size(); i++)
                            {
                                dataList.add(dataCacheList2.get(i));
                            }
                        }
                        else {
                            dataList.clear();
                        }
                    }
                    adapter.notifyDataSetChanged();
                    mPullDownView.notifyDidRefresh();
                    break;
                case WHAT_DID_MORE:
                    List<HashMap<String, String>> dataMoreList = (List<HashMap<String, String>>) msg.obj;
                    if (dataMoreList == null)
                    {
                        dataMoreList = new ArrayList<HashMap<String, String>>();
                    }
                    if (dataList != null && dataList.size() != 0)
                    {
                        // 新的List组成，新加载的加上原来的列表
                        dataList.addAll(dataMoreList);
                    }
                    adapter.notifyDataSetChanged();
                    mPullDownView.notifyDidMore();
                    break;
                case 4:
                    mPullDownView.changeFoot(0, "没有更多信息了");
                case 999:
                    List<HashMap<String, String>> dataNewList1 = (List<HashMap<String, String>>) msg.obj;
                    if (dataNewList1 != null)
                    {
                        adapter.notifyDataSetChanged();;
                        mPullDownView.notifyDidLoad();

                    }
                default:
                    break;
            }
        }
    }

    class MyCustomAdapter extends BaseAdapter
    {
        private Context main;

        private List<HashMap<String, String>> list;

        public MyCustomAdapter(Context main, List<HashMap<String, String>> list)
        {
            this.main = main;
            this.list = list;
        }

        public int getCount()
        {
            return list.size();
        }

        public Object getItem(int position)
        {
            return list.get(position);
        }

        public long getItemId(int position)
        {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent)
        {
            // 如果未选择或list列表为空时直接跳出，避免NullPointException
            if (position < 0 || list.size() <= 0)
            {
                return null;
            }
//             如果为空重新导入ListView的布局文件，布局文件自定义
            if (convertView == null)
            {
                convertView = LayoutInflater.from(main).inflate(R.layout.listitemillegal, null);
            }

            TextView t1 = (TextView)convertView.findViewById(R.id.t1);
            TextView t2 = (TextView)convertView.findViewById(R.id.t2);
            TextView t3 = (TextView)convertView.findViewById(R.id.t3);
            TextView t4 = (TextView)convertView.findViewById(R.id.t4);
            TextView t5 = (TextView)convertView.findViewById(R.id.t5);
            ImageView readImg = (ImageView)convertView.findViewById(R.id.readImg);

            if (list.get(position).get("IS_READ").toString().equals("1"))
            {
                readImg.setVisibility(View.INVISIBLE);
            }
            else{
                readImg.setVisibility(View.VISIBLE);
            }

            t1.setText("储罐代码："+list.get(position).get("TANK_CODE").toString());
            t2.setText(list.get(position).get("COMPANY_NAME").toString());
            t3.setText("超范围");
            t4.setText(list.get(position).get("ALARM_INFO").toString());
            t5.setText(list.get(position).get("ALARM_DATE").toString());


            return convertView;
        }
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
